package handle_client;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;


public class SocketPool {
	private static final int CLIENT_DELEGATE = 1000;
	private static final int FILE_DELEGATE = 1001;
	
	private int ports;
	private static SocketPool pool;
	
	private SocketPool(int PORTS){
		super();
	
		this.ports = PORTS;
	}
	
	//接受连接
	public void acceptConnection()
	{
		try{
			ServerSocket seversocket = new ServerSocket(ports);
			
			while(true)
			{
				Socket socket = seversocket.accept();
				ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
				ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
				int type = in.readInt();
				int user_number = in.readInt();
				if(type == CLIENT_DELEGATE){
					ClientDelegate client_delegate = new ClientDelegate(out,user_number);
					ClientDelegate.client_delegates.add(client_delegate);
					Thread thread = new Thread(new ClientHandler(socket));
					System.out.println(socket.isClosed());
					thread.start();
				}else if(type == FILE_DELEGATE){
					int sender_number = in.readInt();
					String file_name = (String) in.readObject();
					FileDelegate file_client = new FileDelegate(user_number,sender_number,socket,file_name);
					file_client.start();
				}
			}
		}catch(IOException e){
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	//建立唯一的Socket池
	
	public static SocketPool CreatePool(int PORTS)
	{
		if(pool == null)
			return new SocketPool(PORTS);
		pool.ports = PORTS;
		return pool;
	}
	
	
	public static void main(String[] args)
	{
		SocketPool pool = SocketPool.CreatePool(2000);
		pool.acceptConnection();
	}
	
}
